package com.gzhryc.shared_device.common;

import com.gzhryc.common.logging.Logger;

import java.util.concurrent.*;

public class BusyThreadPool {
	
	static Logger log = Logger.getLogger(BusyThreadPool.class);

	static BusyThreadPool me;
	
	public static BusyThreadPool self() {
		if(me == null) {
			me = new BusyThreadPool();
		}
		return me;
	}

	ThreadPoolExecutor executorService;
	// 创建一个单线程的ScheduledExecutorService
    ScheduledExecutorService scheduledExecutorService;
	
	public void initial() {
		if(executorService != null) {
			executorService.shutdown();
			executorService = null;
		}
		int poolSize = Runtime.getRuntime().availableProcessors();
		BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(64);
		RejectedExecutionHandler policy = new ThreadPoolExecutor.AbortPolicy();
		//可堵塞的线程池队列
		executorService = new ThreadPoolExecutor(poolSize, poolSize * 2, 180, TimeUnit.SECONDS,queue,policy);
		
		if(scheduledExecutorService != null) {
			scheduledExecutorService.shutdown();
			scheduledExecutorService = null;
		}
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
	}
	
	public void execute(Runnable runnable) {
		if (executorService != null) {
			try {
				executorService.execute(runnable);
			} catch (Exception e) {
				log.error("繁忙线程池添加新任务失败，丢失任务", e);
			}
		}else {
			log.error("繁忙线程池未初始化");
		}
	}
	
	public void execute(Runnable runnable,long delay,TimeUnit unit) {
		if (scheduledExecutorService != null) {
			try {
				scheduledExecutorService.schedule(runnable,delay,unit);
			} catch (Exception e) {
				log.error("添加延迟处理任务失败，丢失任务", e);
			}
		}else {
			log.error("延迟处理服务未初始化");
		}
	}
}
